<template>
  <div class="customer-made mb32">
    <header class="jzt-flex-bt pb20">
      <div class="left jzt-flex-center">
        <img class="mr8" src="@/assets/images/customMade-icon.png" width="24" height="24" lt="" />
        <p class="f18 jzt-pf-bold">
          我要定制商品<span class="f14 jzt-pf-medium" style="color: #86909c">（换颜色，换材质，改尺寸定制）</span>
        </p>
      </div>
      <div class="right">
        <el-icon class="action-icon f24" :class="{ close: !open }" @click="clickIcon"><CloseBold /></el-icon>
      </div>
    </header>
    <div v-if="open" class="content pt20 pb20 mb20">
      <div class="custom-item jzt-flex-bt" v-for="(item, index) in customList" :key="index">
        <div class="left jzt-flex-start" style="width: 100%; flex-wrap: nowrap">
          <div
            class="name-button text-over"
            :class="{ active: selected.map(obj => obj.templateDetailId).includes(item.templateDetailId) }"
            :title="item.specificationText"
            @click="clickNameButton(item)"
          >
            <div class="text-over">
              {{ item.specificationText || "--" }}

              <div class="active-icon">
                <div>
                  <el-icon><Select /></el-icon>
                </div>
              </div>
            </div>
          </div>
          <div class="custom-content ml32">
            <div class="jzt-flex-start">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="增减定制值：增加（正数输入如‘1’）、减小（负数输入如‘-1’）"
                placement="top"
              >
                <el-button class="mr2" link>
                  <el-icon style="color: #c0c4cc"><QuestionFilled /></el-icon>
                </el-button>
              </el-tooltip>
              <p class="mr8" style="color: #4e5969; width: 40px; min-width: 40px">
                增减<img class="ml4" src="@/assets/images/add-del.png" width="8px" height="11px" alt="" />
              </p>
              <div class="number-input-wrap mr10">
                <el-input-number
                  v-model="item.newItems"
                  class="jzt-input-number jzt-input-number-hidden"
                  controls-position="right"
                  style="width: 134px"
                  @change="countCustomPrice(null, item)"
                />
                <i class="unit f12">{{ useCodeArrStore().getDictName("shop_unit", item.productUnit) }}</i>
              </div>
              <div class="custom-price-wrap">
                <p class="f12 jzt-flex-bt">
                  <span v-if="item.oneCustomPrice">
                    单项定制价：<span style="color: #ff3333">¥{{ item.oneCustomPrice || "-" }}</span>
                  </span>
                  <span v-else>单项定制价：--</span>

                  <el-button class="f12" type="primary" link style="color: #213270" @click="openDrawer(item)">标准说明</el-button>
                </p>
                <p class="f12" style="color: #86909c; line-height: 12px">
                  <span
                    class="text-over"
                    v-if="Number(item.newItems) > 0"
                    style="display: inline-block; transform: scale(0.8); margin-left: -22px; width: 236px; line-height: 12px"
                    :title="` 每增加${item.addNum}${useCodeArrStore().getDictName('shop_unit', item.productUnit)}单价：¥${
                      item.addAmount
                    }`"
                  >
                    每增加{{ item.addNum }}{{ useCodeArrStore().getDictName("shop_unit", item.productUnit) }}单价：¥{{
                      item.addAmount
                    }}
                  </span>
                  <span
                    class="text-over"
                    v-else
                    style="display: inline-block; transform: scale(0.8); margin-left: -22px; width: 236px; line-height: 12px"
                    :title="`每减少${item.reduceNum}${useCodeArrStore().getDictName('shop_unit', item.productUnit)}单价：¥${
                      item.reduceAmount
                    }`"
                  >
                    每减少{{ item.reduceNum }}{{ useCodeArrStore().getDictName("shop_unit", item.productUnit) }}单价：¥{{
                      item.reduceAmount
                    }}
                  </span>
                </p>
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="right">
          <el-button class="f12" type="primary" link style="color: #213270" @click="openDrawer(item)">标准说明</el-button>
        </div> -->
      </div>
    </div>
    <footer v-if="open" class="jzt-flex-bt">
      <div class="left jzt-flex-center">
        <p class="jzt-pf-medium" style="color: #4e5969">商品数量：</p>
        <p class="mr20 jzt-pf-medium">
          1{{
            postData?.skuList?.length > 0 ? useCodeArrStore().getDictName("shop_unit", postData?.skuList[0]?.productUnit) : "--"
          }}
          <!-- <el-input-number v-model="shangpinNum" :min="0" size="default" placeholder="请输入" class="ml10 mr10" />套 -->
        </p>
        <el-tooltip
          :visible="visible"
          popper-class="customer-detail-popper"
          class="box-item"
          effect="light"
          placement="bottom"
          trigger="click"
        >
          <el-button
            :disabled="selected.length <= 0"
            class="customer-detail-btn"
            type="primary"
            link
            @click="visible = !visible"
            style="color: #213270"
          >
            定制明细<img
              class="ml5"
              :class="{ open: visible }"
              src="@/assets/images/arrow-top-icon.png"
              width="16"
              height="16"
              alt=""
            />
          </el-button>
          <template #content>
            <div class="selected-item jzt-flex-bt" v-for="(item, index) in selected" :key="index">
              <p class="jzt-pf-medium">{{ item.specificationText }}</p>
              <p class="jzt-pf-medium">
                增减数值：{{ item.newItems }}{{ useCodeArrStore().getDictName("shop_unit", item.productUnit) }}
              </p>
            </div>
          </template>
        </el-tooltip>
      </div>
      <div class="right">
        <p class="f18 jzt-pf-bold" style="color: #3d3d3d">
          定制价格合计：<span style="color: #ff3333">¥{{ dingzhiPriceTotal }}</span>
        </p>
      </div>
    </footer>

    <!-- 清空取消定制商品数据的二次确认 提示弹窗 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenReset"
      title=""
      message="确定要取消定制商品？"
      submitBtnText="继续"
      @submit="resetData"
    >
      <template #message>
        <p class="f16">确定要取消定制商品？</p>
      </template>
    </ActionSubmitDialog>

    <!-- 标准说明 -->
    <el-drawer v-model="drawer" size="480" class="jzt-drawer custom-standard-remark" :before-close="handleClose">
      <template #header>
        <p class="f18" style="color: #131414">{{ currCustom.specificationText + "-标准说明" }}</p>
      </template>
      <div class="remark-content">
        <Editor v-model="currCustom.standardText" :isEdit="false" :height="-210" />
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, nextTick, computed, inject } from "vue";
import { CloseBold, QuestionFilled } from "@element-plus/icons-vue";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import Editor from "@/components/Editor";
import useCodeArrStore from "@/store/modules/select";

const isChainTenant = JSON.parse(localStorage.getItem("userinfo"))?.isChainTenant; //判断是否是加盟商
const emit = defineEmits(["returnPriceTotal"]);
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  postData: {
    type: Object,
    default: () => {}
  },
  skuObj: {
    type: Object,
    default: () => {}
  }
});

const visible = ref(false);
const open = ref(false);
const _isOpenReset = ref(false);
const selected = ref([]);
const customList = computed(() => {
  return props.list;
});
const currCustom = ref({});
const drawer = ref(false); //标准说明抽屉
const shangpinNum = ref(0); //定制商品数量
const dingzhiPriceTotal = ref("0"); //定制价格合计

/**更换sku之后，重新计算定制价格 */
const resetCustomPrice = clinetRealPrice => {
  customList.value?.map((item, index) => {
    countCustomPrice(clinetRealPrice, item, index < customList.value.length - 1 ? false : true);
  });
};

/**计算单项定制价 */
const countCustomPrice = (clinetRealPrice, row, countTotal = true) => {
  if (Number(row.newItems) > 0) {
    row.oneCustomPrice =
      (Math.abs(Number(row.newItems)) / Number(row.addNum)) * Number(row.addAmount) * Number(props.postData?.coefficient);
    if (isChainTenant) {
      /**如果是加盟商，单项定制价还要乘一个agtRate系数 */
      row.oneCustomPrice = Number(row.oneCustomPrice) * Number(props.postData?.agtRate);
    }
  } else {
    row.oneCustomPrice =
      (Math.abs(Number(row.newItems)) / Number(row.reduceNum)) * Number(row.reduceAmount) * Number(props.postData?.coefficient);
    if (isChainTenant) {
      /**如果是加盟商，单项定制价还要乘一个agtRate系数 */
      row.oneCustomPrice = Number(row.oneCustomPrice) * Number(props.postData?.agtRate);
    }
  }
  countTotal && countCustomPriceTotal(clinetRealPrice); //计算定制价格合计
  console.log("计算单项定制价格1111", row.oneCustomPrice);
};
/**计算定制价格合计 */
const countCustomPriceTotal = clinetRealPrice => {
  let customPrice = 0;
  dingzhiPriceTotal.value = 0;
  selected.value?.map(item => {
    customPrice += item.oneCustomPrice || 0;
  });
  dingzhiPriceTotal.value =
    selected.value.length > 0 ? customPrice + (Number(clinetRealPrice) || Number(props.skuObj?.clinetRealPrice || 0)) : "0";
  console.log("计算定制价格合计22222", dingzhiPriceTotal.value, props.skuObj);
  emit("returnPriceTotal", dingzhiPriceTotal.value);
};

/**定位到“定制说明” */
const toCustomRemark = inject("toCustomRemark");

const openDrawer = row => {
  currCustom.value = row;
  drawer.value = true;
};

const handleClose = () => {
  drawer.value = false;
};

const clickNameButton = row => {
  const idArr = selected.value.map(item => item.templateDetailId);
  if (idArr.includes(row.templateDetailId)) {
    const arr = selected.value.filter(item => item.templateDetailId !== row.templateDetailId);
    selected.value = arr;
  } else {
    selected.value.push(row);
  }
  toCustomRemark(); //定位到“定制说明”
  countCustomPriceTotal(); //计算定制价格合计
  console.log("选中的定制项222", selected.value);
};

const clickIcon = () => {
  if (open.value) {
    _isOpenReset.value = true;
  } else {
    open.value = !open.value;
  }
};

/**关闭定制模块，并且清空选中的定制模版和填写的定制信息 */
const resetData = () => {
  open.value = false; //关闭定制模块
  _isOpenReset.value = false; //关闭二次提醒框

  selected.value = []; //重置选中的定制规则数组
  customList.value.map(item => {
    item.newItems = null; //重置定制规则"增减数值"
    item.oneCustomPrice = null; //重置“单项定制价”
  });
  shangpinNum.value = 0; //重置商品数量
  dingzhiPriceTotal.value = 0; //重置定制价格合计
};

/**获取选中定制项 */
const getSelectedCustom = () => {
  return selected.value;
};

defineExpose({ resetCustomPrice, getSelectedCustom });
</script>

<style lang="scss">
.customer-detail-popper {
  width: 400px;
  padding: 10px 16px !important;
  .selected-item {
    line-height: 40px;
    background-color: #f5f7fa;
    padding: 0 20px;
    &:not(:last-of-type) {
      margin-bottom: 10px;
    }
  }
}
.custom-standard-remark {
  .el-drawer__header {
    border-bottom: 1px solid #dcdfe6;
    padding-bottom: 24px !important;
  }
}
</style>
<style lang="scss" scoped>
.custom-price-wrap {
  width: 192px;
}
:deep(.jzt-input-number.el-input-number.is-controls-right) {
  &.jzt-input-number-hidden {
    .el-input__wrapper {
      padding-right: 60px !important;
    }
  }
}

.remark-content {
  :deep(.w-e-scroll) {
    background-color: white !important;
    border: 1px solid #e4e7ed;
    border-top: none;
    border-radius: 0 0 4px 4px;
  }
  :deep(.editor-com) {
    & > div {
      border: none !important;
      & > div:first-of-type {
        border: 1px solid #e4e7ed;
        border-bottom-color: #e4e7ed !important;
        background-color: #f5f7fa;
        border-radius: 4px 4px 0 0;
        .w-e-bar {
          background: transparent;
          height: 44px;
          display: flex;
          align-items: center;
        }
        .w-e-bar-item button:hover {
          background-color: #e5ebf1;
        }
      }
    }
  }
}
.customer-made {
  header {
    border-bottom: 1px solid #e1e6ed;
    .right {
      height: 24px;
      .action-icon {
        transition: all 0.5s;
      }
      .close {
        transform: rotate(45deg);
        transition: all 0.5s;
      }
    }
  }
  .content {
    border-bottom: 1px solid #e1e6ed;
    .custom-item:not(:last-of-type) {
      margin-bottom: 24px;
    }
    .name-button {
      width: 120px;
      min-width: 120px;
      line-height: 40px;
      color: #86909c;
      border-radius: 3px;
      text-align: center;
      box-sizing: border-box;
      cursor: pointer;
      position: relative;
      border: 1px solid transparent;
      & > div {
        border: 1px solid #dcdfe6;
        padding: 0 10px;
      }
      &.active {
        border: none;
        & > div {
          border: 2px solid #041830;
        }
      }
      .active-icon {
        display: none;
        position: absolute;
        right: 2px;
        bottom: 1px;
        & > div {
          position: relative;
          width: 14px;
          height: 14px;
          .el-icon {
            font-size: 12px;
            position: absolute;
            top: -1px;
            left: -2px;
            color: white;
            transform: scale(0.7);
          }
        }
      }
      &.active {
        .active-icon {
          border: 8px solid transparent;
          border-bottom-color: #041830;
          border-right-color: #041830;
          width: 0;
          height: 0;
          display: flex;
          align-items: flex-start;
          justify-content: flex-start;
        }
      }
      // &.active {
      //   border: 1px solid #ff8928;
      //   color: #ff8928;
      // }
    }
    .custom-content {
      .number-input-wrap {
        position: relative;
        .unit {
          position: absolute;
          right: 6px;
          top: 1px;
          color: #4e5969;
          font-style: normal;
          width: 48px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: flex-end;
        }
      }
    }
  }
  footer {
    .right {
      font-weight: bold;
    }
    :deep(.el-input-number) {
      .el-input-number__decrease,
      .el-input__wrapper {
        background-color: white !important;
      }
      .el-input-number__decrease {
        background-color: white;
        border-radius: 4px;
        border: 1px solid #dcdcdc;
        &:hover ~ .el-input:not(.is-disabled) .el-input__wrapper {
          box-shadow: none;
        }
      }
      .el-input-number__increase {
        background-color: white;
        border-radius: 4px;
        border: 1px solid #dcdcdc;
        &:hover ~ .el-input:not(.is-disabled) .el-input__wrapper {
          box-shadow: none;
        }
      }
      .el-input__wrapper {
        box-shadow: none !important;
      }
      .el-input__inner {
        background-color: white;
        border-radius: 4px;
        border: 1px solid #dcdcdc;
      }
    }
    :deep(.customer-detail-btn.el-button) {
      img {
        transition: all 0.5s;
      }
      img.open {
        transform: rotate(180deg);
        transition: all 0.5s;
      }
    }
  }
}
</style>
